package club.itstudio.itouc.controller.jw.course

import club.itstudio.itouc.core.exception.ITOUCException
import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.service.JwOps
import club.itstudio.itouc.util.Redis
import org.springframework.web.bind.annotation.CookieValue
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController

@RestController
class Plan (val redis: Redis,
            val jwOps: JwOps){

    @GetMapping("/jw/course/plan/{year}/{specialtyNum}")
    fun getPlanCourse(@CookieValue token: String,
                      @PathVariable year: String,
                      @PathVariable specialtyNum: String): Result<Any> {
        val session = jwOps.getJwSession(token)
        val userCode = session.userCode
        val userSpecialtyNum = userCode.substring(2, 8)
        val planCourses = try {
            redis.getPlanCourse(year, specialtyNum)
        }catch (e: ITOUCException) {
            session.refresh()
            jwOps.getPlanCourse(session, year, specialtyNum).also {
                if (userSpecialtyNum == specialtyNum) {
                    redis.savePlanCourse(year, specialtyNum, it)
                }
            }
        }
        return ResultUtil.success(planCourses)
    }
}